<?php
declare (strict_types=1);

namespace app\technician_api\controller;

use think\facade\Log;
use Throwable;
use ba\ClickCaptcha;
use think\facade\Config;
use think\facade\Validate;
use app\common\facade\Token;
use app\admin\model\AdminLog;
use app\common\controller\Technician;
use think\facade\Db;

class Withdrawal extends Technician
{
    protected array $noNeedLogin = [];
    protected array $noNeedPermission = ['*'];
    protected $model;

    public function initialize (): void
    {
        parent::initialize();
        $this->model = new \app\technician_api\model\Withdrawal;
    }

    /**
     * 发起提现
     */
    public function create ()
    {
        $params = $this->request->param();

        $validate = \think\facade\Validate::rule([
            'price|提现金额'     => 'require',
            'card_id|银行卡信息' => 'require',
        ]);

        if (!$validate->check($params)) {
            $this->error($validate->getError());
        }

        $user = Db::table("ba_technician")
            ->where([
                'technician_id' => $this->auth->technician_id
            ])
            ->find();

        if (!$user)
            $this->error("查询用户信息失败");
        if ($user['money'] < $params['price']) {
            $this->error("账户余额不足");
        }
        $card = Db::table("ba_card")
            ->where([
                'card_id'       => $params['card_id'],
                'technician_id' => $this->auth->technician_id
            ])
            ->count();
        if ($card < 1) {
            $this->error("银行卡信息获取失败");
        }

        // 启动事务
        Db::startTrans();
        try {
            Db::table("ba_technician")
                ->where([
                    'technician_id' => $this->auth->technician_id
                ])
                ->update([
                    "money" => (floatval($user['money']) - floatval($params['price']))
                ]);

            $save = $this->model
                ->create([
                    'price'         => $params['price'],
                    'card_id'       => $params['card_id'],
                    'technician_id' => $this->auth->technician_id,
                    'status'        => 0,
                    'area_id'       => $user['area_id'],
                ]);

            Db::table("ba_technician_money_log")
                ->save([
                    'technician_id' => $this->auth->technician_id,
                    'money'         => $params['price'],
                    'before'        => $user['money'],
                    'after'         => (floatval($user['money']) - floatval($params['price'])),
                    'memo'          => '技师发起提现申请, 减少余额',
                    'create_time'   => date("Y-m-d H:i:s", time()),
                    'type'          => 3,
                    'order_id'      => 0,
                    'withdrawal_id' => $save->withdrawal_id
                ]);


            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            Log::error("提现失败：technician_id :{$this->auth->technician_id} errMsg:{$e->getMessage()}");
            $this->error("申请失败");
        }
        $this->success("申请成功");
    }

    /**
     * 技师提现审核状态列表
     */
    public function index ()
    {
        $rows = $this->model
            ->order("create_time", "desc")
            ->where('technician_id', $this->auth->technician_id)

            ->with(['card'])
            ->paginate(10)
            ->append(['status_text']);
        $this->success("", $rows);
    }

}